import 'dart:async';

import 'package:flutter/services.dart';

typedef LogCallback<T> = void Function(T);

class LogcatUtils {

  final MethodChannel _channel = const MethodChannel('LogcatViewerPlugin/controrller');
  final EventChannel _eventChannel = const EventChannel('LogcatViewerPlugin/listen');

  // late String _logs = "";
  late int maxLogCount = 10000;// 暂时定为1万个log信息，减轻内存压力，可调整

  late List<LogCallback<List<String>>> _listenerList = [];

  late List<String> _LogList = [];
  late List<String> _filterLogList = [];

  late StreamSubscription _subscription;

  late bool _newFilter = false;
  late String _filterStr = "";

  static LogcatUtils? _instance;

  static LogcatUtils get instance {
    _instance ??= LogcatUtils();
    return _instance!;
  }

  // static Future<String?> get platformVersion async {
  //   final String? version = await _channel.invokeMethod('startLogInfo');
  //   return version;
  // }

  //开启 native 轮询
  startLog() async {
    _channel.invokeMethod("startLogInfo");
    _onListenLogData();
  }

  //关闭 native 轮询
  stopLog() async {
    _channel.invokeMethod("stopLogInfo");
  }

  //监听 native event 数据流
  void _onListenLogData() {
    _subscription = _eventChannel.receiveBroadcastStream().distinct((a, b) {
      return a == b;
    }).listen((data) {
      // if (_logs.length > maxLogCount) {
      //   // 删掉第一行，否则，就是，从后往前的 第 10 万个字符
      //   int subStartIndex = _logs.indexOf("\n\n");/**/
      //   if (subStartIndex < 0) {
      //     subStartIndex = _logs.length - maxLogCount;
      //   }
      //   _logs = _logs.substring(subStartIndex);
      // }
      //   _logs += "${data as String}\n\n";// 拼接log
      if (_LogList.length >= maxLogCount) {
        _LogList.removeAt(0);
      }
      _LogList.add(data/*"${data}"*/);
      _updateInfo();

      // onEvent?.call(data as String);
    }, onError: (e){
      print(e);
    });
  }

  _updateInfo() {
    var returnList = _LogList;
    if (_filterStr.isNotEmpty) {
      // print("_newFilter = $_newFilter");
      String data = _LogList.isNotEmpty ? _LogList.last : "";
      if (_newFilter) {// 如果筛选文字变化了
        _newFilter = false;
        _filterLogList.clear();
      }
      if (_filterLogList.isEmpty) {// 筛选结果列表为空的时候，
        for (var element in _LogList) {
          if (element.contains(_filterStr) && !_filterLogList.contains(element)) {
            _filterLogList.add(element);
          }
        }
      } else if (data.contains(_filterStr)) {// 筛选结果列表不为空的时候，判断当前的数据是否满足筛选条件
        _filterLogList.add(data);
      }
      returnList = _filterLogList;
    } else if (_filterLogList.isNotEmpty) {
      _filterLogList.clear();
    }

    for (var element in _listenerList) {
      element.call(returnList);
    }

  }

  setFilterStr(String filter) {
    _newFilter = _filterStr != filter;
    _filterStr = filter;
  }

  addListener(LogCallback<List<String>> listener) {
    _listenerList.add(listener);
  }
  removeListener(LogCallback<List<String>> listener){
    _listenerList.remove(listener);
  }
  clearListener(){
    _listenerList.clear();
  }

  clearLog() {
    _LogList.clear();
    _filterLogList.clear();
    _updateInfo();
  }

  cancelListen() {
    _subscription.cancel();
  }
}
